﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Clojure;
public class SGTrigger 
{
   public string Desc;
   protected bool IsRuning  = false;
   protected int  CurActioni = 0;
   protected bool IsWaitAction = false;

   public List<TriggerEvent> TriggerEvents =new List<TriggerEvent>();   
   public ASTNode ConditionNode; 
   public List<BaseAction> ActionNodes;

   List<TriggerInstance> RunningInstances = new List<TriggerInstance>();

   public Context ClojureContext;

   public SGTrigger() 
   {
       this.ClojureContext = new Context(GameTrigger.Instance.ClojureContext);
   }

   public virtual void OnTrigger(Unit triggerUnit) 
   {
       this.ClojureContext.Define("TriggerUnit",new ObjectNode(triggerUnit));
       if (IsEvent() && IsCondition()) 
       {
           RunActions(triggerUnit);
       }
   }
   public bool IsEvent() 
   {
       for (int i = 0; i < TriggerEvents.Count; i++)
       {
           if (TriggerEvents[i].EventCondition())
           {
               return true;
           }
       }
       return false;
   }

   public bool IsCondition() 
   {
       if (ConditionNode == null) 
       {
           return true;
       }
      return ((BoolNode)RT.Evaluate(ConditionNode,this.ClojureContext)).Val;
   }
   public void AddEvent(TriggerEvent triggerEvent)  
   {
       this.TriggerEvents.Add(triggerEvent);
   }

   public void RunActions(Unit triggerUnit) 
   {
       this.GetRunInstance().Run(triggerUnit);
       if (this.IsRuning == false) 
       {
           this.IsRuning = true;
           this.CurActioni = 0;
           this.IsWaitAction =false;
       }
   }
   public TriggerInstance GetRunInstance() 
   {
       TriggerInstance freeInstance = null;
       for (int i = 0; i < this.RunningInstances.Count;i++)
       {
           if (this.RunningInstances[i].IsRunning == false) 
           {
              freeInstance = this.RunningInstances[i];
              return freeInstance;
           }
       }
       TriggerInstance newInstance = new TriggerInstance(this);
       newInstance.trigger = this;
       this.RunningInstances.Add(newInstance);
       return newInstance;
   }

   public virtual void Update() 
   {
       for (int i = 0; i < this.RunningInstances.Count;i++)
       {
           this.RunningInstances[i].Update();
       }  
   }
}
